var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fs = require('fs');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const multer = require('multer');
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);

const uploadsDir = path.join(__dirname, 'uploads');
//判断目录是否存在，如果不存在则创建
function createDir(dirName){
  if(!fs.existsSync(dirName)){
    fs.mkdirSync(dirName);
  }
}
// 设置存储上传文件的位置和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    createDir(uploadsDir);
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    console.log(file);
    cb(null, `${Date.now()}-${path.extname(file.originalname)}`);//带有空格、括号类的名字无法正常压缩，把文件名改为时间戳+后缀名格式
  }
});

// 只接受上传的图片文件
const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'));
    }
  }
});

app.post('/upload', upload.single('image'), async (req, res) => {  
  try {
    // 获取上传的文件路径
    const filePath = path.normalize(req.file.path).replace(/\\/g, '\/');
    var reName = path.basename(filePath);
    const files = await imagemin([filePath], {
      destination: 'public/compressed',
      plugins: [
        imageminMozjpeg({
          quality: 70 // 可以设置1到100之间的任何整数值
        }),
        imageminPngquant({
          quality: [0.4, 0.5]
        })
      ]
    });
    console.log(files[0]);
    console.log('public/compressed/'+reName,'public/compressed/'+ req.file.originalname);
    // 返回处理结果和压缩后的图片 URL
    fs.renameSync('public/compressed/'+reName,'public/compressed/'+ req.file.originalname);//重新改为原文件名
    res.json({ success: true, data:[{url: `/compressed/${req.file.originalname}`, size: files[0].data.length}]});

  } catch (error) {
    console.error(error);
    res.status(500).json({ success: false, error: '图片处理失败' });
  }
});


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
